package com.yoke.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoke.util.JsonUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * Created by jiangzeyin on 2017/5/18.
 */
@Service
public class UserService {
    @Resource
    BaseService baseService;

    /**
     * 登录
     *
     * @param name
     * @param pwd
     * @return
     * @throws IOException
     */
    public boolean login(String name, String pwd) throws IOException {
//        String path = SystemBean.getInstance().getEnvironment().getProperty("order.conf");
//        String filePath = String.format("%s/conf/customer/info.conf", path);
        File file = baseService.getCustomerInfoFile();
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(file.getPath());
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name_ = jsonObject.getString("name");
            String pwd_ = jsonObject.getString("pwd");
            if (name.equals(name_) && pwd.equals(pwd_))
                return true;
        }
        return false;
    }

    public boolean updatePwd(String name, String pwd) throws IOException {
//        String path = SystemBean.getInstance().getEnvironment().getProperty("order.conf");
//        String filePath = String.format("%s/conf/customer/info.conf", path);
        File file = baseService.getCustomerInfoFile();
        JSONArray jsonArray = (JSONArray) JsonUtil.readJson(file.getPath());
        boolean find = false;
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name_ = jsonObject.getString("name");
            String pwd_ = jsonObject.getString("pwd");
            if (name.equals(name_)) {
                jsonObject.put("pwd", pwd);
                find = true;
            }
        }
        if (find) {
            JsonUtil.saveJson(file.getPath(), jsonArray);
            return true;
        }
        return false;
    }
}
